package com.walle.biz.user;

import com.walle.core.constants.Constants;
import com.walle.core.model.LoginUserInfo;
import com.walle.core.utils.Utils;
import com.walle.dao.user.model.User;
import com.walle.service.common.CacheProxy;
import com.walle.service.user.UserBindService;
import com.walle.service.user.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 用户登录
 */
@Service
public class UserLoginBiz {

    @Resource
    private CacheProxy<String, LoginUserInfo> cacheProxy;

    @Resource
    private UserService userService;

    @Resource
    private UserBindService userBindService;

    /**
     * 模拟登录
     *
     * @return 登录用户信息
     */
    public LoginUserInfo loginByMock(HttpServletResponse response) {
        // 构建模拟用户
        User user = new User();
        user.setId(1);
        user.setUsername("mock");
        user.setNickname("模拟用户");
        return this.handleLogin(user, response);
    }

    /**
     * 登录
     *
     * @param user 登录用户信息
     * @return LoginUserInfo
     */
    private LoginUserInfo handleLogin(User user, HttpServletResponse response) {
        String token = UUID.randomUUID().toString();
        LoginUserInfo loginUserInfo = new LoginUserInfo();
        BeanUtils.copyProperties(user, loginUserInfo);
        loginUserInfo.setToken(token);
        // 存入缓存
        cacheProxy.put(token, loginUserInfo, Utils.AppConfig.getSession().getExpire());
        // 写入cookie
        if (response != null) {
            Cookie cookie = new Cookie(Constants.HEADER_TOKEN, token);
            cookie.setPath("/");
            cookie.setHttpOnly(Boolean.TRUE);
            response.addCookie(cookie);
        }
        return loginUserInfo;
    }
}
